package com.demo.phonerepair.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.demo.phonerepair.mapper.RepairMapper;
import com.demo.phonerepair.module.RepairQueryModule;
import com.demo.phonerepair.pojo.Repair;
import com.demo.phonerepair.pojo.User;
import com.demo.phonerepair.service.RepairService;
import com.demo.phonerepair.service.UserService;
import com.demo.phonerepair.util.Md5Password;
import com.demo.phonerepair.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RepairServiceImpl extends ServiceImpl<RepairMapper, Repair> implements RepairService {
    @Autowired
    private RepairMapper repairMapper;
    
    // 注入UserService用于查询接待人员
    @Autowired
    private UserService userService;
    
    @Override
    public Result<Map<String, Object>> getRepairListByCondition(RepairQueryModule repairQueryModule){
        //处理分页参数
        int pageNum = repairQueryModule.getPageNum() == null ? 1 : repairQueryModule.getPageNum();
        int pageSize = repairQueryModule.getPageSize() == null ? 10 : repairQueryModule.getPageSize();

        //处理关键词和排序
        String searchKeyword = repairQueryModule.getSearchKeyword() == null ? "" : repairQueryModule.getSearchKeyword();
        String sortField = repairQueryModule.getSortField() == null ? "createAt" : repairQueryModule.getSortField();
        //在getRepairListByCondition方法中添加
        String sortOrder = repairQueryModule.getSortOrder() == null ? "desc" : repairQueryModule.getSortOrder();
        //验证排序方向，防止SQL注入
        if (!"asc".equalsIgnoreCase(sortOrder) && !"desc".equalsIgnoreCase(sortOrder)) {
            sortOrder = "desc";
        }
        //转换为大写以符合SQL标准
        sortOrder = sortOrder.toUpperCase();

        //使用MybatisPlus的Page对象（关键修改
        IPage<Repair> page = new Page<>(pageNum,pageSize);

        //调用Mapper方法
        IPage<Repair>pageResult = repairMapper.selectRepairByCondition(
                (Page<Repair>) page,
                repairQueryModule.getUserId(),
                searchKeyword,
                sortField,
                sortOrder
        );
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("count",pageResult.getTotal());
        responseMap.put("repairRequest",pageResult.getRecords());
        return Result.success(responseMap);
    }

    @Override
    public boolean createRepair(Repair repair) {
        //参数的非空校验
        if (repair.getUserId() == null) {
            return false;
        }
        if (repair.getPhoneModel() == null){
            return false;
        }
        if (repair.getPhoneIssueDescription() == null){
            return false;
        }
        repair.setRequestStatus(1);
        repair.setCreatedAt(LocalDateTime.now());
        repair.setUpdatedAt(LocalDateTime.now());

        return save(repair);
    }
    
    // 实现获取接待人员列表的方法
    @Override
    public List<User> getAllReceptionist() {
        // 假设接待人员的角色ID为"3"（实际应根据系统设计确定）
        // 使用QueryWrapper查询角色ID为3的所有用户
        return userService.list(new QueryWrapper<User>().eq("role_id", "3"));
    }

    @Override
    public boolean deleteRepair(Integer repairId, Integer userId, String password){
        if(repairId == null){
            return false;
        }
        if(userId == null){
            return false;
        }
        User user = userService.getById(userId);
        if(password == null){
            return false;
        }
        if(user == null){
            return false;
        }
        if(!Md5Password.generateMD5(password).equals(user.getUserPasswordHash())){
            return false;
        }
        Boolean result = repairMapper.deleteRepairByIdAndUserId(repairId,userId) > 0;
        return result;
    }
}
